package com.jdy.haoduoai.parse;

import com.jdy.haoduoai.util.LeXiaoXiaoBanLog;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;

import java.util.Collection;

/**
 * @author hufei
 *
 */
public class JsonSerializer {

  private static final String TAG = JsonSerializer.class.getName();

  private static JsonSerializer instance = new JsonSerializer();

  private ObjectMapper impl;

  public static JsonSerializer getInstance() {
    if (instance == null)

    {
      instance = new JsonSerializer();
    }
    return instance;
  }

  JsonSerializer() {
    try {
      impl = new ObjectMapper();
    } catch (Exception e) {
      e.printStackTrace();
    }
    DeserializationConfig cfg = impl.getDeserializationConfig();
    cfg.set(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  }

  public String serialize(Object object) {
    try {
      return impl.writeValueAsString(object);
    } catch (Exception e) {
      LeXiaoXiaoBanLog.e(TAG, e.getMessage());
      return null;
    }
  }

  public <T> T deserialize(String json, Class<T> clazz) {
    if (json == null || json.length() == 0) {
      return null;
    }
    try {
      return impl.readValue(json, clazz);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  public <T extends Collection<?>, V> Object deserialize(String json,
      Class<T> collection, Class<V> data) {
    try {
      return impl.readValue(json, TypeFactory.collectionType(collection, data));
    } catch (Exception e) {
      LeXiaoXiaoBanLog.e(TAG, e.getMessage());
      return null;
    }
  }

  public <T> T convert(Object from, Class<T> to) {
    if (from == null) {
      return null;
    }
    try {
      return impl.convertValue(from, to);
    } catch (Exception e) {
      LeXiaoXiaoBanLog.e(TAG, e.getMessage());
      return null;
    }
  }

  public <T extends Collection<?>, V> Object convert(Object from,
      Class<T> collection, Class<V> data) {
    try {
      return impl.convertValue(from,
          TypeFactory.collectionType(collection, data));
    } catch (Exception e) {
      LeXiaoXiaoBanLog.e(TAG, e.getMessage());
      return null;
    }
  }
}
